package com.wing.product.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.constant.SecurityConstants;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.dao.WarehouseMoveInventoryDao;
import com.wing.product.dao.WarehouseSettledDao;
import com.wing.product.model.entity.*;
import com.wing.product.model.response.MoveInventoryVO;
import com.wing.product.model.response.WarehouseProductInventoryVO;
import com.wing.product.model.response.WarehouseProductVO;
import com.wing.product.service.*;
import com.wing.user.model.entity.SelContactInfo;
import com.wing.user.service.SelContactInfoService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.security.OAuthFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品入库表(warehouse_product_inventory)表控制层
 *
 * @author xxxxx
 */
@Api(value = "移库记录明细管理", tags = "#/warehouse/product/warehouseMoveInventory")
@RestController("warehouseMoveInventoryController")
@RequestMapping("/warehouse/moveInventory")
public class WarehouseMoveInventoryController {
    /**
     * 服务对象
     */
    @Autowired
    private WarehouseProductInventoryService warehouseProductInventoryService;


    @Autowired
    private WarehouseMoveInventoryService warehouseMoveInventoryService;

    @Autowired
    private WarehouseMoveInventoryDao warehouseMoveInventoryDao;

    @Autowired
    private WarehouseProductMarkService warehouseProductBrandService;

    @Autowired
    private WarehouseProductVarietyService warehouseProductVarietyService;

    @Autowired
    private WarehouseProductProducerService warehouseProductProducerService;

    @Autowired
    private WarehouseSettledService warehouseSettledService;

//    @PostMapping("/upload-excel")
//    public String uploadWithHeader(@RequestParam("file") MultipartFile file) throws IOException {
    public String uploadWithHeader1(@RequestParam("file") MultipartFile file) throws IOException {

        EasyExcel.read(file.getInputStream(), new ReadListener<Map<String, String>>() {
                    @Override
                    public void invoke(Map<String, String> data, AnalysisContext context) {

                        Integer rowIndex = context.readRowHolder().getRowIndex();
                        // 这里的key是表头名称
                        System.out.println("读取到第"+rowIndex+"行数据: " + data);


//                        // 示例：通过表头名称获取数据
//                        String name = data.get("姓名");
//                        String age = data.get("")
                        WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
                        Map maps=warehouseMoveInventoryDao.findSpace(data.get(7));

                        if(ObjectUtil.isNotEmpty(maps)){
                            warehouseProductInventory.setWarehouseAreaId(Long.parseLong(maps.get("warehouseAreaId").toString()));
                            warehouseProductInventory.setWarehouseShelfSpaceId(Long.parseLong(maps.get("id").toString()));
                            warehouseProductInventory.setWarehouseId(Long.parseLong(maps.get("warehouseId").toString()));
                        }else{
                            System.out.println(rowIndex+"库位号不存在");
                        }

                        Map mapc=warehouseMoveInventoryDao.findCustomer(data.get(0));
                        if(ObjectUtil.isNotEmpty(mapc)){
                            warehouseProductInventory.setCustomerId(Long.parseLong(mapc.get("id").toString()));
                            warehouseProductInventory.setOriginalCustomerId(Long.parseLong(mapc.get("id").toString()));
                        }else{
                            System.out.println(rowIndex+"货主名称不存在");
                        }

                        warehouseProductInventory.setInventoryTypeId(Long.parseLong("1553312018094096413"));
//                        warehouseProductInventory.setWarehouseOrderId(1L);
//                        warehouseProductInventory.setProductMainUnitId(1L);
                        warehouseProductInventory.setQuantity(1);//
                        warehouseProductInventory.setProductStatus(3);
//                        warehouseProductInventory.setProductType(1);
//                        warehouseProductInventory.setProduct_producer_id(1);
                        warehouseProductInventory.setGrossWeight(Double.parseDouble(data.get(5)));//
                        warehouseProductInventory.setNetWeight(Double.parseDouble(data.get(5)));//
                        warehouseProductInventory.setUserBundleCode(data.get(3));//
                        warehouseProductInventory.setSysBundleCode(UniqueIdGeneratorUtil.generateUniqueId("BC-", "yyyyMMddHHmmss", 1000, 9999));
//                        warehouseProductInventory.setSource("1");
                        warehouseProductInventory.setSpecifications(data.get(4));//

                        // 定义与输入字符串匹配的格式
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                        // 转换为LocalDateTime（时间部分默认为0）
                        LocalDateTime dateTime = LocalDate.parse(data.get(13).toString(), formatter).atStartOfDay();
                        warehouseProductInventory.setStartTime(dateTime);


//                        warehouseProductInventory.setThirdPartyLocation(data.get("宝盈通库位号"));//
//                        warehouseProductInventory.setInboundOrderNumber(data.get("入库单号"));//
                        warehouseProductInventory.setRemarks( data.get(12));
                        warehouseProductInventory.setGoodsType(data.get(11));
//                        warehouseProductInventory.setSpecThickness(data.get("规格厚度"));
//                        warehouseProductInventory.setSpecWidth(data.get("规格宽度"));
//                        warehouseProductInventory.setSpecLength(data.get("规格长度"));
//                        warehouseProductInventory.setPoundWeight(data.get("磅重"));
//                        warehouseProductInventory.setPackagingMethod(data.get("包装方式"));
//                        warehouseProductInventory.setFirstEntryDate(LocalDateTime.parse(data.get("首次入库时间")));
//                        warehouseProductInventory.setMaterialManagementNumber(data.get("原料管理号"));
//                        warehouseProductInventory.setInboundMethod(data.get("入库方式"));
//                        warehouseProductInventory.setProductMaterialCategory(data.get("材质"));
//                        warehouseProductInventory.setCustomerInboundDate(LocalDateTime.parse(data.get("库户入库日期")));
//                        warehouseProductInventory.setAvailableWeight(data.get("可供重量"));
//                        warehouseProductInventory.setAvailableQuantity(data.get("可供件数"));
//                        warehouseProductInventory.setLabelPrinted(data.get("标签打印"));



                        Map map=warehouseMoveInventoryDao.findMark(data.get(8));//
                        if(ObjectUtil.isNotEmpty(map)){
                            warehouseProductInventory.setWarehouseProductMark(map.get("id").toString());
                        }else{
                            System.out.println(rowIndex+"钢种不存在");
//                            WarehouseProductMark warehouseProductMark=new WarehouseProductMark();
//                            warehouseProductMark.setMarkCode(data.get("钢种"));
//                            warehouseProductMark.setMarkName(data.get("钢种"));
//                            warehouseProductMark.setContractPrice(0.0);
//                            warehouseProductMark.setMemberPrice(0.0);
//                            warehouseProductMark.setDensity(data.get("密度"));
//                            warehouseProductBrandService.save(warehouseProductMark);
                        }

                        Map map1=warehouseMoveInventoryDao.findVariety(data.get(10));//
                        if(ObjectUtil.isNotEmpty(map1)){
                            warehouseProductInventory.setWarehouseProductVariety(map1.get("id").toString());
                        }else{
//                            WarehouseProductVariety warehouseProductVariety = new WarehouseProductVariety();
//                            warehouseProductVariety.setVarietyName(data.get("品种"));
//                            warehouseProductVariety.setVarietyCode(data.get("品种"));
//                            warehouseProductVariety.setContractPrice(0.0);
//                            warehouseProductVariety.setMemberPrice(0.0);
//                            warehouseProductVarietyService.save(warehouseProductVariety);
                            System.out.println(rowIndex+"品种不存在");
                        }

                        Map map2=warehouseMoveInventoryDao.findProducer(data.get(9));
                        if(ObjectUtil.isNotEmpty(map2)){
                            warehouseProductInventory.setWarehouseProductProducer(map2.get("id").toString());
                        }else{
//                            WarehouseProductProducer warehouseProductProducer=new WarehouseProductProducer();
//                            warehouseProductProducer.setProducerCode(data.get("产地"));
//                            warehouseProductProducer.setProducerName(data.get("产地"));
//                            warehouseProductProducerService.save(warehouseProductProducer);
                            System.out.println(rowIndex+"产地不存在");
                        }
                        warehouseProductInventoryService.save(warehouseProductInventory);

                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                        System.out.println("文件读取完成");
                    }
                })
                .headRowNumber(1) // 指定表头所在行(从0开始计数)
                .sheet()
                .doRead();

        return "文件读取开始";
    }


    @ApiOperation(value = "产品移动库位", notes = "产品移动库位")
    @PostMapping("/movingInventory")
    public JsonResult movingInventory(MoveInventoryVO MoveInventoryVO) {
         boolean res= warehouseMoveInventoryService.movingInventory(MoveInventoryVO);
         if(res){
             return JsonResult.success("操作成功");
         }
            return JsonResult.fail("操作失败");
        }


    @ApiOperation(value = "仓库列表", notes = "仓库列表")
    @GetMapping("/factoryList")
    public JsonResult<List<MoveInventoryVO>> factoryList() {

        List<MoveInventoryVO> moveInventoryVOList=warehouseProductInventoryService.factoryList();
        return JsonResult.success("操作成功",moveInventoryVOList);
    }

    @ApiOperation(value = "库区列表", notes = "库区列表")
    @GetMapping("/areaList")
    public JsonResult<List<MoveInventoryVO>> areaList(String id) {
        return JsonResult.success(warehouseProductInventoryService.areaList(id));
    }

    @ApiOperation(value = "库位列表", notes = "库位列表")
    @GetMapping("/spaceList")
    public JsonResult<List<MoveInventoryVO>> spaceList(String id) {
        return JsonResult.success(warehouseProductInventoryService.spaceList(id));
    }


    @ApiOperation(value = "查询所有", notes = "查询")
    @GetMapping("/list")
    public PageResult<MoveInventoryVO> list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page
            , @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit
            , @RequestParam(value = "sort", defaultValue = "create_time", required = false) String sort
            , @RequestParam(value = "order", defaultValue = "asc", required = false) String order
            , @RequestParam(value = "notIds[]", required = false) List<Integer> notIds
           ) {
        Page<WarehouseMoveInventory> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        IPage<MoveInventoryVO> list = warehouseMoveInventoryService.list4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @PostMapping("/upload-excel")
    public String uploadWithHeader(@RequestParam("file") MultipartFile file) throws IOException, InterruptedException {
        List<CustomersInfoEntity> customersInfoEntities=warehouseMoveInventoryDao.findAllCustomer();
        if(customersInfoEntities.size()>0){
            List<String> list =new ArrayList<String>();
            for(CustomersInfoEntity customersInfoEntity:customersInfoEntities){
                List<SelContactInfo> selContactInfoList=warehouseMoveInventoryDao.findByCustomerId(customersInfoEntity.getId());
                if(selContactInfoList.size()>0){
                    WarehouseSettledEntity warehouseSettledEntity = new WarehouseSettledEntity();
                    warehouseSettledEntity.setCustomerLevelId(1);
                    warehouseSettledEntity.setSource(2);
                    warehouseSettledEntity.setStatus(0);
                    warehouseSettledEntity.setSettledOrder(UniqueIdGeneratorUtil.generateUniqueId("RZ", "yyyyMMddHHmmss", 1000, 9999));
                    warehouseSettledEntity.setContactId(selContactInfoList.get(0).getId().toString());
                    warehouseSettledEntity.setFactoryId("1560138999936540689");
                    warehouseSettledService.save(warehouseSettledEntity);
                    System.out.println("正在插入企业"+customersInfoEntity.getCustomerName());
                    Thread.sleep(500);
                }
                else{
                    list.add(customersInfoEntity.getCustomerName());
                    System.out.println("企业无联系人"+customersInfoEntity.getCustomerName());
                }

            }
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
        }
        return "";
    }


}
